package com.coke.im.client.net;

import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;

import com.coke.im.client.stream.Message;
import com.coke.im.client.stream.MessageStream;

public class IOClient {

    private MessageStream messageStream;

    private OutputStream opt;
    private Socket cSocket;

    public void start(SocketAddress address) throws Exception {
        cSocket = new Socket();
        cSocket.connect(address, 10000);
        this.messageStream = new MessageStream(cSocket.getInputStream());
        this.opt = cSocket.getOutputStream();
    }

    public void write(Message message) throws Exception {
        this.write(message.toBytes());

    }

    private void write(byte[] bytes) throws Exception {
        this.opt.write(bytes);
    }

    public void close() throws Exception {
        if(this.cSocket!=null){
            this.cSocket.close();
        }
    }

    public Message readMessage() {
        try {
            return messageStream.readMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
